/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.PromotionVo;
import com.rzico.core.entity.*;
import com.rzico.core.service.*;
import com.rzico.exception.CustomException;
import com.rzico.util.CodeGenerator;
import com.rzico.util.DateUtils;
import com.rzico.util.RedisHandler;
import com.rzico.util.StringUtils;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.EnterpriseMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * 产品档案业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class EnterpriseService extends BaseServiceImpl<Enterprise, String> {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired @Lazy
    private MemberService memberService;

    @Autowired @Lazy
    private SysUserService sysUserService;

    @Autowired @Lazy
    private SysMchService sysMchService;

    @Autowired @Lazy
    private SysOfficeService sysOfficeService;

    @Autowired @Lazy
    private SysRoleService sysRoleService;

    @Autowired @Lazy
    private SysRoleMenuService sysRoleMenuService;

    @Autowired @Lazy
    private BrandService brandService;

    @Autowired @Lazy
    private SysEmployeeService sysEmployeeService;

    @Autowired @Lazy
    private SysPostService sysPostService;

    @Autowired @Lazy
    private SupplierService supplierService;

    @Autowired @Lazy
    private SysUserDataScopeService sysUserDataScopeService;

    @Autowired @Lazy
    private SysEmployeePostService sysEmployeePostService;

    @Autowired @Lazy
    private PromotionService promotionService;

    @Autowired @Lazy
    private PromotionGiftService promotionGiftService;

    @Autowired @Lazy
    private CouponService couponService;


    @Autowired @Lazy
    private BomService bomService;
    @Autowired @Lazy
    private BomItemService bomItemService;

    @Autowired @Lazy
    private FreightService freightService;
    @Autowired @Lazy
    private FreightAreaService freightAreaService;

    @Autowired @Lazy
    private CouponTargetService couponTargetService;

    @Autowired @Lazy
    private ProductCategoryService productCategoryService;

    @Autowired @Lazy
    private NavigationService navigationService;

    @Autowired @Lazy
    private AdService adService;

    @Autowired @Lazy
    private ProductService productService;

    @Autowired @Lazy
    private GoodsService goodsService;

    @Autowired @Lazy
    private DesignerService designerService;

    @Autowired @Lazy
    private ShopService shopService;

    @Autowired @Lazy
    private TagService tagService;

    @Autowired @Lazy
    private VipService vipService;

    @Autowired @Lazy
    private WxPageService wxPageService;

    @Autowired @Lazy
    private ProductTagService productTagService;

    @Autowired @Lazy
    private BrandTagService brandTagService;

    @Autowired @Lazy
    private NavigationTagService navigationTagService;

    @Autowired @Lazy
    private AdTagService adTagService;

    @Autowired
    private RedisHandler redisHandler;

    @Override
    public BaseMapper<Enterprise, String> getMapper() {
        return enterpriseMapper;
    }


    @Override
    public int updateByPrimaryKeySelective(Enterprise enterprise) {
        enterprise.setBalance(null);
        return enterpriseMapper.updateByPrimaryKeySelective(enterprise);
    }

    @Transactional(rollbackFor = Exception.class)
    public Enterprise getCurrent() {
        Map<String,String> params = getToken();//获取token
        if (params!=null && params.size()>0) {
            if (StringUtils.isNotEmpty(params.get("hMchId"))) {
                params.put("mchId",params.get("hMchId"));//此hMchId可能为用户修改后传过来的
            } else {
                SysUser sysUser = sysUserService.selectByPrimaryKey(params.get("id"));
                params.put("mchId",sysUser.getMchId());
            }
            if (StringUtils.isNotEmpty(params.get("mchId"))) {
                while (!redisHandler.lock(params.get("mchId"),params.get("mchId"))) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("redis-lock=>"+params.get("mchId"));
                }
                try {
                    //findbymch有缓存
                    Enterprise enterprise = findByMch(params.get("mchId"));
                    if (enterprise != null) {
                        return enterprise;
                    } else {
                        return initEnterprise(sysMchService.selectByPrimaryKey(params.get("mchId")));
                    }
                } finally {
                    redisHandler.unlock(params.get("mchId"),params.get("mchId"));
                }
            }
        }
        return null;
    }

    //一键装修
    @Transactional(rollbackFor = Exception.class)
    public void initISVData(Enterprise enterprise) {

        Enterprise sourceEnterprise = null;
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getIsvId()!=null) {
            //特约商户,服务商代收
            sourceEnterprise = findByMch(sysMch.getIsvId());
        } else {
            throw new CustomException("没有上级单位");
        }

        Map<String,Object> params = new HashMap<>();

        //读取源标签
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Tag> soruceTagList = tagService.selectList(params);

        //删除目标标签
        Tag tag = new Tag();
        tag.setEnterpriseId(enterprise.getId());
        tagService.delete(tag);

        Map<String,Long> tagMap = new HashMap<>();

        for (Tag g:soruceTagList) {
            tag = new Tag();
            tag.setCreateDate(new Date());
            tag.setEnterpriseId(enterprise.getId());
            tag.setName(g.getName());
            tag.setMemo(g.getMemo());
            tag.setType(g.getType());
            tag.setOrders(g.getOrders());
            tagService.insertUseGeneratedKeys(tag);

            tagMap.put(String.valueOf(g.getId()),tag.getId());
        }

        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Vip> soruceVipList = vipService.selectList(params);

        //删除目标标签
        Vip vip = new Vip();
        vip.setEnterpriseId(enterprise.getId());
        vipService.delete(vip);

        for (Vip g:soruceVipList) {
            vip = new Vip();
            vip.setCreateDate(new Date());
            vip.setEnterpriseId(enterprise.getId());
            vip.setName(g.getName());
            vip.setMemo(g.getMemo());
            vip.setVipType(g.getVipType());
            vip.setVip(g.getVip());
            vip.setMethod(g.getMethod());
            vip.setAmount(g.getAmount());
            vip.setPeople(g.getPeople());
            vip.setQuantity(g.getQuantity());
            vipService.insertUseGeneratedKeys(vip);
        }

        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<WxPage> wxPageList = wxPageService.selectList(params);

        WxPage wxPage = new WxPage();
        wxPage.setEnterpriseId(enterprise.getId());
        wxPageService.delete(wxPage);

        Designer designer = new Designer();
        designer.setEnterpriseId(enterprise.getId());
        designerService.delete(designer);

        Map<String,Long> wxPageMap = new HashMap<>();

        for (WxPage page:wxPageList) {

            wxPage = new WxPage();
            wxPage.setCreateDate(new Date());
            wxPage.setPageType(page.getPageType());
            wxPage.setEnterpriseId(enterprise.getId());
            wxPage.setName(page.getName());
            wxPage.setDescription(page.getDescription());
            wxPage.setThumbnial(page.getThumbnial());
            wxPage.setOrders(page.getOrders());
            if (page.getTagId()!=null) {
                wxPage.setTagName(page.getName());
                wxPage.setTagId(tagMap.get(String.valueOf(page.getTagId())));
            }
            wxPageService.insertUseGeneratedKeys(wxPage);

            wxPageMap.put(String.valueOf(page.getId()),wxPage.getId());

            params.clear();
            params.put("enterpriseId",sourceEnterprise.getId());
            params.put("pageId",page.getId());
            List<Designer> sourceDesignerList = designerService.selectList(params);

            for (Designer d:sourceDesignerList) {
                designer = new Designer();
                designer.setCreateDate(new Date());
                designer.setPageId(wxPage.getId());
                designer.setEnterpriseId(enterprise.getId());
                designer.setDataType(d.getDataType());
                designer.setName(d.getName());
                designer.setOrders(d.getOrders());
                designer.setRows(d.getRows());
                String[] tagIds = d.getTagids().split(",");
                List<String> ids = new ArrayList<>();
                for (String tagId:tagIds) {
                    if (!"".equals(tagId) && tagId!=null) {
                        ids.add(String.valueOf(tagMap.get(tagId)));
                    }
                }
                String tagStr = org.apache.commons.lang3.StringUtils.join(ids,",");
                designer.setTagids(tagStr);
                designer.setTitle(d.getTitle());
                designerService.insertUseGeneratedKeys(designer);
            }

        }

        //初始化分类
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<ProductCategory> sourceProductCategoryList = productCategoryService.selectList(params);

        ProductCategory productCategory = new ProductCategory();
        productCategory.setEnterpriseId(enterprise.getId());
        productCategoryService.delete(productCategory);
        Map<String,Long> productCategoryMap = new HashMap<>();

        List<ProductCategory> productCategoryList = new ArrayList<>();

        for (ProductCategory g:sourceProductCategoryList) {
            productCategory = new ProductCategory();
            productCategory.setCreateDate(new Date());
            productCategory.setEnterpriseId(enterprise.getId());
            productCategory.setName(g.getName());
            productCategory.setIsShow(g.getIsShow());
            productCategory.setThumbnail(g.getThumbnail());
            productCategoryService.insertUseGeneratedKeys(productCategory);

            productCategory.setParentId(g.getParentId());
            productCategory.setTreePath(g.getTreePath());
            productCategoryMap.put(String.valueOf(g.getId()),productCategory.getId());

            productCategoryList.add(productCategory);
        }

        //重组ID

        for (ProductCategory pc:productCategoryList) {
            pc.setParentId(productCategoryMap.get(String.valueOf(pc.getParentId())));

            String [] treePathList = pc.getTreePath().split(",");
            List<String> ids = new ArrayList<>();
            for (String tagId:treePathList) {
                if (!"".equals(tagId) && tagId!=null) {
                    ids.add(String.valueOf(productCategoryMap.get(tagId)));
                }
            }
            String treePathStr = org.apache.commons.lang3.StringUtils.join(ids,",");
            pc.setTreePath(","+treePathStr+",");
            productCategoryService.updateByPrimaryKey(pc);
        }


        //初始化品牌
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        params.put("deleted",0);
        List<Brand> sourceBrandList = brandService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        brandTagService.deleteList(params);

        Brand brand = new Brand();
        brand.setEnterpriseId(enterprise.getId());
        brandService.delete(brand);

        Map<String,Long> brandMap = new HashMap<>();

        for (Brand n:sourceBrandList) {
            brand = new Brand();
            BeanUtils.copyProperties(n, brand);
            brand.setEnterpriseId(enterprise.getId());
            brandService.insertUseGeneratedKeys(brand);

            brandMap.put(String.valueOf(n.getId()),brand.getId());

            params.clear();
            params.put("enterpriseId",sourceEnterprise.getId());
            params.put("brands",n.getId());
            List<BrandTag> sourceBrandTagList = brandTagService.selectList(params);
            for (BrandTag bt:sourceBrandTagList) {
                BrandTag brandTag = new BrandTag();
                brandTag.setBrands(brand.getId());
                brandTag.setTags(tagMap.get(String.valueOf(bt.getTags())));
                brandTagService.insert(brandTag);
            }

        }

        //初始化运费模板
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Freight> sourceFreightList = freightService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        freightAreaService.deleteList(params);

        Freight freight = new Freight();
        freight.setEnterpriseId(enterprise.getId());
        freightService.delete(freight);
        Map<String,Long> freightMap = new HashMap<>();

        for (Freight f:sourceFreightList) {
            freight = new Freight();
            BeanUtils.copyProperties(f, freight);
            freight.setEnterpriseId(enterprise.getId());

            freightService.insertUseGeneratedKeys(freight);

            freightMap.put(String.valueOf(f.getId()),freight.getId());

            params.clear();
            params.put("freightId",f.getId());
            List<FreightArea> sourceFreightAreaList = freightAreaService.selectList(params);
            for (FreightArea fa:sourceFreightAreaList) {
                FreightArea freightArea = new FreightArea();
                BeanUtils.copyProperties(fa, freightArea);

                freightArea.setFreightId(freight.getId());
                freightAreaService.insertUseGeneratedKeys(freightArea);

            }
        }

        //初始化商品
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Goods> sourceGoodsList = goodsService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        productTagService.deleteList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        goodsService.deleteList(params);

        Product product = new Product();
        product.setEnterpriseId(enterprise.getId());
        productService.delete(product);

        Map<String,Long> productMap = new HashMap<>();
        Map<String,Long> goodsMap = new HashMap<>();

        for (Goods g:sourceGoodsList) {

            Goods gd = new Goods();
            gd.setCreateDate(new Date());
            gd.setTotalSale(0L);
            gd.setHits(0L);
            gd.setScore(0);
            gd.setReview(0L);
            goodsService.insertUseGeneratedKeys(gd);

            goodsMap.put(String.valueOf(g.getId()),gd.getId());

            params.clear();
            params.put("enterpriseId",sourceEnterprise.getId());
            params.put("goodsId",g.getId());
            params.put("deleted",0);
            List<Product> sourceProductList = productService.selectList(params);
            List<Product> goodsProductList = new ArrayList<>();

            for (Product prod:sourceProductList) {

                product = new Product();
                BeanUtils.copyProperties(prod, product);
                product.setId(null);
                product.setGoodsId(gd.getId());

                if (prod.getBrandId()!=null) {
                    product.setBrandId(brandMap.get(String.valueOf(prod.getBrandId())));
                }
                if (prod.getFreightId()!=null) {
                    product.setFreightId(freightMap.get(String.valueOf(prod.getFreightId())));
                }

                product.setProductCategoryId(productCategoryMap.get(String.valueOf(prod.getProductCategoryId())));

                product.setSupplierId(null);
                product.setDistributionId(null);
                product.setEnterpriseId(enterprise.getId());
                if (!product.getSubType().equals(0)) {
                    product.setMinLimit(0);
                    product.setFreightId(null);
                }
                productService.insertUseGeneratedKeys(product);

                productMap.put(String.valueOf(prod.getId()),product.getId());

                params.clear();
                params.put("enterpriseId",sourceEnterprise.getId());
                params.put("products",prod.getId());
                List<ProductTag> sourceProductTagList = productTagService.selectList(params);
                for (ProductTag bt:sourceProductTagList) {
                    ProductTag productTag = new ProductTag();
                    productTag.setProducts(product.getId());
                    productTag.setTags(tagMap.get(String.valueOf(bt.getTags())));
                    productTagService.insert(productTag);
                }
                goodsProductList.add(product);

            }


            Long mainProductId = 0L;
            for (Product gp : goodsProductList){
                if (gp.getIsList()){
                    mainProductId = gp.getId();
                    break;
                }
            }

            for (Product gp : goodsProductList) {
                if (!gp.getUnitType().equals(0)) {
                    gp.setMainProductId(mainProductId);
                } else {
                    gp.setMainProductId(gp.getId());
                }
                productService.updateByPrimaryKeySelective(gp);
            }


        }

        //初始化导航
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Navigation> sourceNavigationList = navigationService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        navigationTagService.deleteList(params);

        Navigation navigation = new Navigation();
        navigation.setEnterpriseId(enterprise.getId());
        navigationService.delete(navigation);

        for (Navigation n:sourceNavigationList) {
            navigation = new Navigation();
            BeanUtils.copyProperties(n, navigation);
            navigation.setEnterpriseId(enterprise.getId());
            if (navigation.getType().equals(1)) {
                navigation.setTypeId(productCategoryMap.get(String.valueOf(n.getTypeId())));
            }
            if (navigation.getType().equals(2)) {
                navigation.setTypeId(wxPageMap.get(String.valueOf(n.getTypeId())));
            }
            if (navigation.getType().equals(3)) {
                navigation.setTypeId(productMap.get(String.valueOf(n.getTypeId())));
            }
            navigationService.insertUseGeneratedKeys(navigation);

            params.clear();
            params.put("enterpriseId",sourceEnterprise.getId());
            params.put("navigations",n.getId());
            List<NavigationTag> sourceNavigationTagList = navigationTagService.selectList(params);
            for (NavigationTag bt:sourceNavigationTagList) {
                NavigationTag navigationTag = new NavigationTag();
                navigationTag.setNavigations(navigation.getId());
                navigationTag.setTags(tagMap.get(String.valueOf(bt.getTags())));
                navigationTagService.insert(navigationTag);
            }

        }


        //初始化广告
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Ad> sourceAdList = adService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        adTagService.deleteList(params);

        Ad ad = new Ad();
        ad.setEnterpriseId(enterprise.getId());
        adService.delete(ad);

        for (Ad n:sourceAdList) {
            ad = new Ad();
            BeanUtils.copyProperties(n, ad);
            ad.setEnterpriseId(enterprise.getId());

            if (ad.getType().equals(9)) {
                ad.setTypeId(wxPageMap.get(String.valueOf(n.getTypeId())));
            }
            if (ad.getType().equals(0)) {
                ad.setTypeId(productMap.get(String.valueOf(n.getTypeId())));
            }
            adService.insertUseGeneratedKeys(ad);


            params.clear();
            params.put("enterpriseId",sourceEnterprise.getId());
            params.put("ads",n.getId());
            List<AdTag> sourceAdTagList = adTagService.selectList(params);
            for (AdTag bt:sourceAdTagList) {
                AdTag adTag = new AdTag();
                adTag.setAds(ad.getId());
                adTag.setTags(tagMap.get(String.valueOf(bt.getTags())));
                adTagService.insert(adTag);
            }

        }

        //初始化活动
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        params.put("status",1);
        List<Coupon> sourceCouponList = couponService.selectList(params);


        params.clear();
        params.put("enterpriseId",enterprise.getId());
        couponTargetService.deleteList(params);

        Coupon coupon = new Coupon();
        coupon.setEnterpriseId(enterprise.getId());
        couponService.delete(coupon);

        Map<String,Long> couponMap = new HashMap<>();

        for (Coupon n:sourceCouponList) {
            coupon = new Coupon();
            BeanUtils.copyProperties(n, coupon);
            coupon.setEnterpriseId(enterprise.getId());
            if (n.getGoods()!=null) {
                coupon.setGoods(goodsMap.get(String.valueOf(n.getGoods())));
            }
            if (n.getProductId()!=null) {
                coupon.setProductId(productMap.get(String.valueOf(n.getProductId())));
            }
            couponService.insertUseGeneratedKeys(coupon);

            couponMap.put(String.valueOf(n.getId()),coupon.getId());

            params.clear();
            params.put("promotionId",n.getId());
            List<CouponTarget> sourceCouponTargetList = couponTargetService.selectList(params);
            for (CouponTarget gift:sourceCouponTargetList) {
                CouponTarget g = new CouponTarget();
                BeanUtils.copyProperties(gift, g);
                g.setCouponId(coupon.getId());
                //商品券
                if (coupon.getTargetType().equals(4)) {
                    g.setTargetId(goodsMap.get(String.valueOf(gift.getTargetId())));
                }
                //品牌券
                if (coupon.getTargetType().equals(1)) {
                    g.setTargetId(brandMap.get(String.valueOf(gift.getTargetId())));
                }
                //分类券
                if (coupon.getTargetType().equals(3)) {
                    g.setTargetId(productCategoryMap.get(String.valueOf(gift.getTargetId())));
                }
                couponTargetService.insertUseGeneratedKeys(g);
            }

        }


        //初始化活动
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        params.put("status",1);
        List<Promotion> sourcePromotionList = promotionService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        promotionGiftService.deleteList(params);

        Promotion promotion = new Promotion();
        promotion.setEnterpriseId(enterprise.getId());
        promotionService.delete(promotion);

        for (Promotion n:sourcePromotionList) {
            promotion = new Promotion();
            BeanUtils.copyProperties(n, promotion);
            promotion.setEnterpriseId(enterprise.getId());
            if (n.getGoodsId()!=null) {
                promotion.setGoodsId(goodsMap.get(String.valueOf(n.getGoodsId())));
            }
            promotionService.insertUseGeneratedKeys(promotion);

            params.clear();
            params.put("promotionId",n.getId());
            List<PromotionGift> sourcePromotionGiftList = promotionGiftService.selectList(params);
            for (PromotionGift gift:sourcePromotionGiftList) {
                PromotionGift g = new PromotionGift();
                BeanUtils.copyProperties(gift, g);
                g.setPromotionId(promotion.getId());
                if (promotion.getGiftType().equals(0)) {
                    g.setGiftId(productMap.get(String.valueOf(gift.getGiftId())));
                }
                if (promotion.getGiftType().equals(1)) {
                    g.setGiftId(couponMap.get(String.valueOf(gift.getGiftId())));
                }
                promotionGiftService.insertUseGeneratedKeys(g);

            }
        }


        //初始化套餐
        params.clear();
        params.put("enterpriseId",sourceEnterprise.getId());
        List<Bom> sourceBomList = bomService.selectList(params);

        params.clear();
        params.put("enterpriseId",enterprise.getId());
        bomItemService.deleteList(params);

        Bom bom = new Bom();
        bom.setEnterpriseId(enterprise.getId());
        bomService.delete(bom);

        for (Bom b:sourceBomList) {
            bom = new Bom();
            BeanUtils.copyProperties(b, bom);
            bom.setEnterpriseId(enterprise.getId());
            if (b.getProductId()!=null) {
                bom.setProductId(productMap.get(String.valueOf(b.getProductId())));
            }
            bomService.insertUseGeneratedKeys(bom);

            params.clear();
            params.put("bomId",b.getId());
            List<BomItem> sourceBomItemList = bomItemService.selectList(params);
            for (BomItem bi:sourceBomItemList) {
                BomItem bomItem = new BomItem();
                BeanUtils.copyProperties(bi, bomItem);
                if (bi.getProductId()!=null) {
                    bomItem.setProductId(productMap.get(String.valueOf(bi.getProductId())));
                }
                bomItem.setBomId(bom.getId());
                bomItemService.insertUseGeneratedKeys(bomItem);

            }
        }

        //  throw new CustomException("error");

    }

    @Transactional(rollbackFor = Exception.class)
    private void initData(Enterprise enterprise) {

        SysMch sysMch = sysMchService.findById(enterprise.getMchId());
        Map<String,Object> params = new HashMap<>();
        params.put("mchId",sysMch.getId());
        List<SysOffice> sysOfficeList = sysOfficeService.selectList(params);

        //初始化公司
        SysOffice sysOffice = new SysOffice();
        if (sysOfficeList.size()>0) {
            sysOffice = sysOfficeList.get(0);
        } else {
            sysOffice.setId(CodeGenerator.getUUID());
            sysOffice.setName(enterprise.getName());
            sysOffice.setStatus(1);
            sysOffice.setPhone(sysMch.getPhone());
            sysOffice.setOfficeName(sysMch.getName());
            sysOffice.setMchId(sysMch.getId());
            sysOffice.setLeader(sysMch.getLinkman());
            sysOffice.setDelFlag(false);
            sysOffice.setAddress(sysMch.getAddress());
            sysOffice.setType(0);
            sysOfficeService.insert(sysOffice);
        }

        //初始化仓库
        params.clear();
        params.put("enterpriseId",enterprise.getId());
        List<Shop> shopList = shopService.selectList(params);
        Shop shop = new Shop();
        if (shopList.size()>0) {
            shop = shopList.get(0);
        } else {
            shop.setEnterpriseId(enterprise.getId());
            shop.setDeleted(false);
            shop.setAreaName(sysMch.getAreaName());
            shop.setAreaId(sysMch.getAreaId());
            shop.setAddress(sysMch.getAddress());
            shop.setLinkman(sysMch.getLinkman());
            shop.setName(sysMch.getName());
            shop.setOfficeId(sysOffice.getId());
            shop.setTelephone(sysMch.getPhone());
            shop.setScopeType(sysMch.getScopeType());

            shop.setStatus(0);
            shop.setType(0);
            shop.setScore(0);
            shop.setMonthSale(0);
            shop.setScopeType(sysMch.getScopeType());
            shopService.insertUseGeneratedKeys(shop);
        }

        //初始化角色

        params.clear();
        params.put("mchId",sysMch.getId());
        List<SysRole> roleList = sysRoleService.selectList(params);

        SysRole sysRole = new SysRole();
        if (roleList.size()>0) {
            sysRole = roleList.get(0);
        } else {

            sysRole.setId(CodeGenerator.getUUID());
            sysRole.setMchId(sysMch.getId());
            sysRole.setName("管理员");
            sysRole.setRemark("拥有最高权限");
            sysRole.setStatus(1);

            sysRoleService.insert(sysRole);

            for (SysMenu menu:sysMch.getMenuList() ) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setId(CodeGenerator.getUUID());
                sysRoleMenu.setRoleId(sysRole.getId());
                sysRoleMenu.setMenuId(menu.getId());
                sysRoleMenuService.insert(sysRoleMenu);
            }

            sysRole.setId(CodeGenerator.getUUID());
            sysRole.setMchId(sysMch.getId());
            sysRole.setName("送货员");
            sysRole.setRemark("只拥用送达权限");
            sysRole.setStatus(1);

            sysRoleService.insert(sysRole);

            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(CodeGenerator.getUUID());
            sysRoleMenu.setRoleId(sysRole.getId());
            sysRoleMenu.setMenuId("5a054ceb09c74f9bb4fa1e782362d237");
            sysRoleMenuService.insert(sysRoleMenu);

            SysRoleMenu sysRoleMenu1 = new SysRoleMenu();
            sysRoleMenu1.setId(CodeGenerator.getUUID());
            sysRoleMenu1.setRoleId(sysRole.getId());
            sysRoleMenu1.setMenuId("82b05379ab7e432fa300b847b4efabce");
            sysRoleMenuService.insert(sysRoleMenu1);

            SysRoleMenu sysRoleMenu2 = new SysRoleMenu();
            sysRoleMenu2.setId(CodeGenerator.getUUID());
            sysRoleMenu2.setRoleId(sysRole.getId());
            sysRoleMenu2.setMenuId("d3911ba4f65b446399f38a2d308df67e");
            sysRoleMenuService.insert(sysRoleMenu2);

            SysRoleMenu sysRoleMenu3 = new SysRoleMenu();
            sysRoleMenu3.setId(CodeGenerator.getUUID());
            sysRoleMenu3.setRoleId(sysRole.getId());
            sysRoleMenu3.setMenuId("c72e0b0c513349e98fdc08274350f9d1");
            sysRoleMenuService.insert(sysRoleMenu3);

        }

        //初始化岗位
        params.clear();
        params.put("mchId",sysMch.getId());
        List<SysPost> postList = sysPostService.selectList(params);

        SysPost sysPost = new SysPost();
        if (postList.size()>0) {
            sysPost = postList.get(0);
        } else {
            sysPost.setId(CodeGenerator.getUUID());
            sysPost.setMchId(sysMch.getId());
            sysPost.setName("本部");
            sysPost.setRemark("系统默认岗位");
            sysPost.setStatus(1);
            sysPost.setDelFlag(false);
            sysPostService.insert(sysPost);
        }

        SysUser sysUser = sysUserService.findById(sysMch.getAdminId());

        //初始化员工
        SysEmployee sysEmployee = new SysEmployee();
        params.clear();
        params.put("mchId",sysMch.getId());
        List<SysEmployee> sysEmployeeList = sysEmployeeService.selectList(params);
        if (sysEmployeeList.size()>0) {
            sysEmployee = sysEmployeeList.get(0);
        } else {
            sysEmployee.setName("店主");
            sysEmployee.setEmpNo("0001");
            sysEmployee.setDelFlag(false);
            sysEmployee.setId(CodeGenerator.getUUID());
            sysEmployee.setMchId(sysMch.getId());
            sysEmployee.setOfficeId(sysOffice.getId());
            sysEmployee.setOfficeName(sysOffice.getName());
            sysEmployee.setStatus(1);
            sysEmployee.setUserId(sysUser.getId());
            sysEmployeeService.insert(sysEmployee);

            SysEmployeePost sysEmployeePost = new SysEmployeePost();
            sysEmployeePost.setEmployeeId(sysEmployee.getId());
            sysEmployeePost.setId(CodeGenerator.getUUID());
            sysEmployeePost.setPostId(sysPost.getId());
            sysEmployeePostService.insert(sysEmployeePost);

        }

        //初始化数据权限

        SysUserDataScope userDataScope = new SysUserDataScope();
        userDataScope.setId(CodeGenerator.getUUID());
        userDataScope.setOfficeId(sysOffice.getId());
        userDataScope.setScopeType(1);
        userDataScope.setUserId(sysUser.getId());
        sysUserDataScopeService.insert(userDataScope);

        userDataScope = new SysUserDataScope();
        userDataScope.setId(CodeGenerator.getUUID());
        userDataScope.setOfficeId(String.valueOf(shop.getId()));
        userDataScope.setScopeType(2);
        userDataScope.setUserId(sysUser.getId());
        sysUserDataScopeService.insert(userDataScope);

        //初始化供应商
        Supplier supplier = new Supplier();
/*
        supplier.setUserId(sysMch.getAdminId());
        supplier.setUsername(sysUser.getUsername());
*/
        supplier.setAddress(sysMch.getAddress());
        supplier.setAreaId(sysMch.getAreaId());
        supplier.setAreaName(sysMch.getAreaName());
        supplier.setConsignee(sysMch.getLinkman());
        supplier.setCode(sysMch.getId());
        supplier.setDeleted(false);
        supplier.setEnterpriseId(enterprise.getId());
        supplier.setMobile(sysMch.getPhone());
        supplier.setPhone(sysMch.getPhone());
        supplier.setTax(BigDecimal.ZERO);
        supplier.setTaxType(0);
        supplier.setName("本部");
        supplierService.insertUseGeneratedKeys(supplier);

        WxPage wxHome = new WxPage();
        params.clear();
        params.put("enterpriseId",enterprise.getId());
        List<WxPage> wxPageList = wxPageService.selectList(params);
        if (wxPageList.size()>0) {
            wxHome = wxPageList.get(0);
        } else {
            wxHome.setPageType(0);
            wxHome.setEnterpriseId(enterprise.getId());
            wxHome.setName("首页");
            wxHome.setDescription("店铺首页（不能删除）");
            wxHome.setThumbnial(enterprise.getLogo());
            wxHome.setOrders(99);
            wxPageService.insertUseGeneratedKeys(wxHome);
        }

        //初始化标签
        Tag glide = new Tag();
        glide.setEnterpriseId(enterprise.getId());
        glide.setName("轮播图");
        glide.setMemo("首页轮播图");
        glide.setType(8);
        glide.setOrders(1);
        tagService.insertUseGeneratedKeys(glide);

        Tag promotion = new Tag();
        promotion.setEnterpriseId(enterprise.getId());
        promotion.setName("活动图");
        promotion.setMemo("活动宣传图");
        promotion.setType(8);
        promotion.setOrders(2);
        tagService.insertUseGeneratedKeys(promotion);

        Tag category = new Tag();
        category.setEnterpriseId(enterprise.getId());
        category.setName("分类");
        category.setMemo("分类导航");
        category.setType(9);
        category.setOrders(1);
        tagService.insertUseGeneratedKeys(category);

        Tag tab = new Tag();
        tab.setEnterpriseId(enterprise.getId());
        tab.setName("发现");
        tab.setMemo("店铺最新动态");
        tab.setType(9);
        tab.setOrders(2);
        tagService.insertUseGeneratedKeys(tab);

        Tag tag1 = new Tag();
        tag1.setEnterpriseId(enterprise.getId());
        tag1.setName("精选");
        tag1.setMemo("猜你喜欢");
        tag1.setType(3);
        tag1.setOrders(1);
        tagService.insertUseGeneratedKeys(tag1);

        Tag tag2 = new Tag();
        tag2.setEnterpriseId(enterprise.getId());
        tag2.setName("热销");
        tag2.setMemo("当季好物");
        tag2.setType(3);
        tag2.setOrders(2);
        tagService.insertUseGeneratedKeys(tag2);

        Tag tag3 = new Tag();
        tag3.setEnterpriseId(enterprise.getId());
        tag3.setName("特惠");
        tag3.setMemo("特卖促销");
        tag3.setType(3);
        tag3.setOrders(3);
        tagService.insertUseGeneratedKeys(tag3);

        Tag tag4 = new Tag();
        tag4.setEnterpriseId(enterprise.getId());
        tag4.setName("新品");
        tag4.setMemo("商品上新");
        tag4.setType(3);
        tag4.setOrders(4);
        tagService.insertUseGeneratedKeys(tag4);

        Tag tag5 = new Tag();
        tag5.setEnterpriseId(enterprise.getId());
        tag5.setName("好评");
        tag5.setMemo("买家好评");
        tag5.setType(3);
        tag5.setOrders(5);
        tagService.insertUseGeneratedKeys(tag5);


        //初始化活动页

        WxPage wxPage = new WxPage();
        wxPage.setPageType(1);
        wxPage.setEnterpriseId(enterprise.getId());
        wxPage.setName("活动精选");
        wxPage.setDescription("福利知时节，为您精选时令商品");
        wxPage.setThumbnial(enterprise.getLogo());
        wxPage.setOrders(1);
        wxPage.setTagName(tab.getName());
        wxPage.setTagId(tab.getId());
        wxPageService.insertUseGeneratedKeys(wxPage);


        //开始装修首页,按行业类型来
        Designer designer = new Designer();
        designer.setPageId(wxHome.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(8);
        designer.setName("swipers");
        designer.setOrders(1);
        designer.setRows(5);
        designer.setTagids(String.valueOf(glide.getId()));
        designer.setTitle("轮播图");
        designerService.insertUseGeneratedKeys(designer);
        designer = new Designer();
        designer.setPageId(wxHome.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(9);
        designer.setName("xcxAd");
        designer.setOrders(2);
        designer.setRows(10);
        designer.setTagids(String.valueOf(category.getId()));
        designer.setTitle("分类导航");
        designerService.insertUseGeneratedKeys(designer);
        designer = new Designer();
        designer.setPageId(wxHome.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(9);
        designer.setName("acrossAd");
        designer.setOrders(3);
        designer.setRows(5);
        designer.setTagids(String.valueOf(tab.getId()));
        designer.setTitle("活动精选");
        designerService.insertUseGeneratedKeys(designer);
        designer = new Designer();
        designer.setPageId(wxHome.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(3);
        designer.setName("products");
        designer.setOrders(3);
        designer.setRows(50);
        designer.setTagids(String.valueOf(tag1.getId())+","+String.valueOf(tag2.getId())+","+String.valueOf(tag3.getId())+","+String.valueOf(tag4.getId())+","+String.valueOf(tag5.getId()));
        designer.setTitle("商品列表");
        designerService.insertUseGeneratedKeys(designer);

        //开始装修发现页
        designer.setPageId(wxPage.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(8);
        designer.setName("banner");
        designer.setOrders(1);
        designer.setRows(1);
        designer.setTagids(String.valueOf(promotion.getId()));
        designer.setTitle("活动宣传图");
        designerService.insertUseGeneratedKeys(designer);
        designer = new Designer();
        designer.setPageId(wxPage.getId());
        designer.setEnterpriseId(enterprise.getId());
        designer.setDataType(3);
        designer.setName("products");
        designer.setOrders(2);
        designer.setRows(50);
        designer.setTagids(String.valueOf(tag3.getId()));
        designer.setTitle("活动商品列表");
        designerService.insertUseGeneratedKeys(designer);

    }

    @Transactional(rollbackFor = Exception.class)
    public Enterprise initEnterprise(SysMch sysMch) {

        //先启动商户入口
        sysMch.setModifyDate(new Date());
        sysMchService.updateByPrimaryKeySelective(sysMch);

        SysUser sysUser = sysUserService.findById(sysMch.getAdminId());

        Member member = null;

        if (sysUser.getMobile()!=null) {

            String username = "mch_" + sysUser.getMchId() + "_" + sysUser.getMobile();

            member = memberService.findByUsername(username);

            if (member == null) {
                member = memberService.register(sysUser,sysMch.getId());
            }

        } else {
            throw new RuntimeException("商户必须绑定手机号");
        }

        Enterprise enterprise = findByMch(sysMch.getId());
        if (enterprise==null) {
            enterprise = new Enterprise();
            enterprise.setCreateDate(new Date());
            enterprise.setModifyDate(new Date());
            enterprise.setAllowReturn(true);
            enterprise.setBrokerage(BigDecimal.ZERO);
            enterprise.setIsLinePay(true);
            enterprise.setBalance(BigDecimal.ZERO);
            enterprise.setTransfer(BigDecimal.ZERO);
            enterprise.setOffLinePay(false);
            enterprise.setPaused(0);
            enterprise.setPaybill(BigDecimal.ZERO);
            enterprise.setScanPay(false);
            enterprise.setShopMaxCount(1L);
            enterprise.setUnionFee(BigDecimal.ZERO);
            enterprise.setShippingMethod(0);
            enterprise.setDeliverMethod("012");
            enterprise.setMinimumDelivery(BigDecimal.ZERO);

            enterprise.setMchId(sysMch.getId());
            enterprise.setName(sysMch.getName());

            if (member!=null) {
                enterprise.setMemberId(member.getId());
            }

            enterprise.setAllowNegativeStock(true);

            super.insertUseGeneratedKeys(enterprise);
            initData(enterprise);


            if (member!=null) {
                member.setEnterpriseId(enterprise.getId());
                member.setMchId(enterprise.getMchId());

                Shop shop = shopService.findByPoint(enterprise,0d,0d);
                member.setShopId(shop.getId());

                memberService.updateByPrimaryKeySelective(member);
            }



        }
        return enterprise;
    }

//    @Cacheable(value = "enterprise", key = "#mchId", unless = "#result eq null")
    public Enterprise findByMch(String mchId) {
/*
        String key = "enterprise:" + mchId;
        Enterprise enterprise = (Enterprise)redisHandler.get(key);
        if (null != enterprise){
            return enterprise;
        }else{
*/
            Map<String,Object> params = new HashMap<>();
            params.put("mchId",mchId);
            List<Enterprise> enterprises = enterpriseMapper.selectList(params);
            if (enterprises.size()>0) {
/*
                redisHandler.set(key, enterprises.get(0), RedisHandler.CACHE_EXPIRED_TIME_TWO_HOURS);
*/
                return enterprises.get(0);
            } else {
                return null;
            }

      /*  }*/

    }

    public Enterprise findByDomain(String domain) {
        Map<String,Object> params = new HashMap<>();
        params.put("domain",domain);
        List<Enterprise> enterprises = enterpriseMapper.selectList(params);
        if (enterprises.size()>0) {
            return enterprises.get(0);
        } else {
            return null;
        }
    }

//    @CachePut(value = "enterprise", key = "#record.mchId", unless = "#result eq null ")
    public Enterprise update(Enterprise record) {
        SysMch sysMch = sysMchService.selectByPrimaryKey(record.getMchId());
        sysMch.setLogo(record.getLogo());
        sysMch.setName(record.getName());
        sysMch.setRemark(record.getNotice());
        sysMchService.updateByPrimaryKeySelective(sysMch);
        Enterprise enterprise = null;
        int affectCount = super.updateByPrimaryKeySelective(record);
        if (affectCount > 0){
            enterprise = this.findById(record.getId());
        }
        return enterprise;
    }

    public BigDecimal calculateFee(Long enterpriseId,BigDecimal amount) {
        Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(enterpriseId);
        return amount.multiply(enterprise.getBrokerage()).multiply(new BigDecimal(0.01)).setScale(2,BigDecimal.ROUND_HALF_DOWN);
    }


    public Boolean checkWorkTime(Long enterpriseId,Date shippingDate) {

        Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(enterpriseId);
        if (enterprise.getShippingConfig() != null) {

            JSONObject config = JSON.parseObject(enterprise.getShippingConfig());
            String workBeginDate = config.getString("workBeginTime");
            String workEndTime = config.getString("workEndTime");

            if (workBeginDate==null || workEndTime==null) {
                return true;
            }

            String timeStr = DateUtils.getTimeStr(shippingDate, DateUtils.SIMPLE_DISPLAY_TIME);

            if (workBeginDate!=null && workEndTime!=null) {
                if (workBeginDate.compareTo(workEndTime)<=0) {
                    return workBeginDate.compareTo(timeStr) < 0 && workEndTime.compareTo(timeStr) >= 0;
                } else {
                    return (workBeginDate.compareTo(timeStr) < 0 && "23:59:59".compareTo(timeStr) >= 0)
                            ||
                           ("00:00:00".compareTo(timeStr) < 0 && workEndTime.compareTo(timeStr) >= 0);
                }
            } else {
                return false;
            }
            
        } else {
            return true;
        }

    }

        public Date calcEstimateDate(Long enterpriseId,Date shippingDate,String weexTime) {

        Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(enterpriseId);
        Date estimateDate = DateUtils.addDate(shippingDate,Calendar.MINUTE,15);

        if (enterprise.getShippingConfig()!=null) {

            JSONObject config = JSON.parseObject(enterprise.getShippingConfig());
            JSONArray speed = null;
            if (config.containsKey("speed")) {
                speed = config.getJSONArray("speed");
            }

//            String workBeginDate = config.getString("workBeginTime");
//            String workEndTime = config.getString("workEndTime");
//
            Boolean isWork = false;

            Integer shippingTime = 15;
            if (config.containsKey("shippingTime")) {
                shippingTime = config.getInteger("shippingTime");
            }
            estimateDate = DateUtils.addDate(shippingDate,Calendar.MINUTE,shippingTime);

            if (speed!=null) {

                for (int i = 0; i < speed.size(); i++) {

                    JSONObject obj = speed.getJSONObject(i);
                    String timeStr = DateUtils.getTimeStr(shippingDate, DateUtils.SIMPLE_DISPLAY_TIME);
                    JSONArray reach = obj.getJSONArray("reach");
                    String beginTime = reach.getString(0);
                    String endTime = reach.getString(1);
                    if (beginTime!=null && endTime!=null && beginTime.compareTo(timeStr) < 0 && endTime.compareTo(timeStr) >= 0) {
                        // {"workBeginTime":"08:00:00","workEndTime":"18:00:00","speed":[{"reach":["00:00:00","00:00:00"],"reachDay":"今天","reachTime":"30分钟"}]}
//                        Integer reachDay = obj.getInteger("reachDay");
                        Integer reachTime = obj.getInteger("reachTime");
                        if (reachTime==null) {
                            reachTime = 15;
                        }
//                        Date d = null

//                        if (reachDay > 0) {
//                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                            try {
//                                d = sdf.parse(DateUtils.getDateStr(shippingDate, DateUtils.HYPHEN_DISPLAY_DATE) + " " + workBeginDate);
//                            } catch (ParseException e) {
//                                e.printStackTrace();
//                            }
//                            ;
//                        } else {
//                            d = shippingDate;
//                        }
//                        if (reachTime > 0) {
//                            d = org.apache.commons.lang3.time.DateUtils.addMinutes(d, reachTime);
//                        }

                        estimateDate = DateUtils.addDate(shippingDate,Calendar.MINUTE,reachTime);
//                        estimateDate = d;
                        isWork = true;

                    }

                }

            }

//            if (isWork==false) {
//                estimateDate = org.apache.commons.lang3.time.DateUtils.truncate(estimateDate,Calendar.DATE);
//            }

        }

//        if (weexTime!=null) {
//            while (true) {
//                String wk = DateUtils.getDayOfWeek(estimateDate);
//                if (weexTime.indexOf(wk)>=0) {
//                    break;
//                }
//                estimateDate = DateUtils.addDate(estimateDate,Calendar.DATE,1);
//            }
//        }

        estimateDate = DateUtils.addDate(estimateDate,Calendar.MINUTE,30);

        return estimateDate;

    }

    public boolean isPaused(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(enterpriseId);
        if (enterprise.getPaused() != null && enterprise.getPaused() == 0) {
            return false;
        } else{
            return true;
        }
    }

    /**
     * 根据id获取营业执照和食品安全
     */
    public Enterprise getEnterpriseById(String enterpriseId) {
        if (StringUtils.isBlank(enterpriseId)) {
            return null;
        }
        return  enterpriseMapper.getEnterpriseById(enterpriseId);
    }
}
